package com.iter.devbox.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 采用fork/join框架计算1+2+3+4的值
 * 
 * @author Jimly
 */
public class CountTask extends RecursiveTask<Integer> {

	private static final long serialVersionUID = -3951205484328499610L;

	private static final int THRESHOLD = 2;
	
	private int start;
	
	private int end;
	
	public CountTask(int start, int end) {
		this.start = start;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		int sum = 0;
		boolean canCompute = (end - start) <= THRESHOLD;
		if (canCompute) {
			for (int i=start; i<=end; i++) {
				sum += i;
			}
		} else {
			//任务大于阀值，则分隔成两个子任务计算
			int middle = (start + end) / 2;
			CountTask leftCountTask = new CountTask(start, middle); 
			CountTask rightCountTask = new CountTask(middle+1, end);
			//执行子任务计算
			leftCountTask.fork();
			rightCountTask.fork();
			//等待子任务计算结束得到计算结果
			int leftResult = leftCountTask.join();
			int rightResult = rightCountTask.join();
			//合并子任务计算结果
			sum = leftResult + rightResult;
		}
		return sum;
	}
	
	public static void main(String[] args) throws Throwable {
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		CountTask countTask = new CountTask(1, 100);
		ForkJoinTask<Integer> fjt = forkJoinPool.submit(countTask);
		int sum = fjt.get();
		System.out.println(sum);
		
		//检查任务执行是否抛出异常
		System.out.println(fjt.getException());
		System.out.println(fjt.isCompletedAbnormally());
	}
}
